package com.junlong0716.enjoylearning.ui

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.PorterDuff
import android.os.Bundle
import android.os.IBinder
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.MotionEvent
import android.view.View
import android.widget.SeekBar
import com.blankj.utilcode.util.ServiceUtils
import com.blankj.utilcode.util.ToastUtils
import com.htxcsoft.corelibrary.glide.GlideUtils
import com.junlong0716.enjoylearning.CommentPresenter
import com.junlong0716.enjoylearning.MyApp
import com.junlong0716.enjoylearning.R
import com.junlong0716.enjoylearning.constant.NetConstant
import com.junlong0716.enjoylearning.dialog.BottomTimerDialog
import com.junlong0716.enjoylearning.entity.rxevent.DownloadSucceedEvent
import com.junlong0716.enjoylearning.entity.rxevent.MusicPlayStateEvent
import com.junlong0716.enjoylearning.entity.rxevent.ProgressEvent
import com.junlong0716.enjoylearning.entity.rxevent.TimeCountDownLeftEvent
import com.junlong0716.enjoylearning.net.api.NetApi
import com.junlong0716.enjoylearning.service.*
import com.junlong0716.enjoylearning.utils.TimeConvertUtils
import com.junlong0716.enjoylearning.widget.PlayPauseDrawable
import com.junlong0716.enjoylearning.widget.PlayerBarView
import com.junlong0716.module.common.base.BaseActivity
import com.junlong0716.module.common.rxbus.Subscribe
import com.junlong0716.module.common.rxbus.ThreadMode
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import jp.wasabeef.glide.transformations.RoundedCornersTransformation
import kotlinx.android.synthetic.main.activity_audio.*
import org.json.JSONObject
import java.text.SimpleDateFormat

class AudioActivity : BaseActivity<AudioPresenter>(), AudioContract.View, View.OnClickListener, PlayMusicCallback {
    //手指按下的点为(x1, y1)手指离开屏幕的点为(x2, y2)
    private var x1 = 0f
    private var x2 = 0f
    private var y1 = 0f
    private var y2 = 0f

    private val currentDuration = SimpleDateFormat("mm:ss")
    private lateinit var playPauseDrawable: PlayPauseDrawable
    private var musicId: Int = 0
    private var musicUrl = ""
    private var flag = 0

    private var musicService: MusicService? = null
    private var mPlayerManager: PlayerManager? = null
    private var currentPosition = 0

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun downloadSucceed(downloadSucceedEvent: DownloadSucceedEvent) {
        if (downloadSucceedEvent.fileId != musicId) {
            return
        }
        tv_download.text = "已下载"
        rl_download.isClickable = false
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun downloadProgress(progressEvent: ProgressEvent) {
        if (progressEvent.knowledgeId != musicId) {
            return
        }

        rl_download.isClickable = false

        tv_download.text = "${(progressEvent.progress.fraction * 100).toInt()}%"
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBus(s: TimeCountDownLeftEvent) {
        if (s.code == 0x8989) {
            tv_timer_close.text = "${TimeConvertUtils.formatDateTime(s.time)}后关闭"

            if (s.time.toInt() == 0) {
                tv_timer_close.text = "定时关闭"
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBus(s: MusicPlayStateEvent) {
        if (s.eventKey == 0x9898) {
            if (s.onPause) {
               mPlayerManager!!.pauseMusic()
            } else {

            }
        }
    }


    override fun beforeSetLayout() {

    }


    override fun attachPresenter() {
        mPresenter = AudioPresenter()
        mPresenter!!.attachView(this)
    }

    override fun getLayoutId(): Int = R.layout.activity_audio



    override fun initView(savedInstanceState: Bundle?) {
        initStartPlayIcon()
        fl_container.setOnClickListener(this)
        fl_back.setOnClickListener(this)
        fl_forward.setOnClickListener(this)
        tv_timer_close.setOnClickListener(this)
        rl_like.setOnClickListener(this)
        rl_download.setOnClickListener(this)
        rl_document.setOnClickListener(this)
        fl_previous.setOnClickListener(this)
        fl_next.setOnClickListener(this)
        rl_share.setOnClickListener(this)
        sb_progress.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                tv_start.text = currentDuration.format(seekBar!!.progress + 1)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                mPlayerManager!!.seekToPosition(seekBar!!.progress)
//                musicService!!.setSeekToPosition(seekBar!!.progress + 1)
//
//                if (flag == 1 && ServiceUtils.isServiceRunning(TimerService::class.java)) {
//                    val timerIntent = Intent()
//                    timerIntent.setClass(this@AudioActivity, TimerService::class.java)
//                    timerIntent.putExtra("TIMER_CLOSE", ((totalDuration1 - seekBar!!.progress) / 1000).toLong())
//                    startService(timerIntent)
//                }
            }
        })




    }

    private fun initStartPlayIcon() {
        playPauseDrawable = PlayPauseDrawable(this, resources.getDimensionPixelSize(R.dimen.pause_bar_player_width).toFloat(), resources.getDimensionPixelSize(R.dimen.pause_bar_player_height).toFloat(), resources.getDimensionPixelSize(R.dimen.pause_bar_player_distance).toFloat())
        playPauseDrawable.setColorFilter(ContextCompat.getColor(this, R.color.text_color_gray_66), PorterDuff.Mode.SRC_IN)
        iv_play.setImageDrawable(playPauseDrawable)
    }

    override fun finish() {
        super.finish()
        this.overridePendingTransition(0, R.anim.anim_down)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event!!.action == MotionEvent.ACTION_DOWN) {
            //当手指按下的时候
            x1 = event.x
            y1 = event.y
        }
        if (event.action == MotionEvent.ACTION_UP) {
            //当手指离开的时候
            x2 = event.x
            y2 = event.y
            if (y2 - y1 > 300) {
                finish()
            }
        }
        return super.onTouchEvent(event)
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.fl_container -> {
                if (mPlayerManager!!.getCurrentMediaPlayerState()) {
                    mPlayerManager!!.pauseMusic()
                } else {
                    mPlayerManager!!.playMusic()
                }
            }
            R.id.fl_back -> {
                mPlayerManager!!.seekToPosition(currentPosition - 15000)
                //musicService!!.setSeekToPosition(musicService!!.getCurrentPosition() - 15000)
            }

            R.id.fl_forward -> {
                mPlayerManager!!.seekToPosition(currentPosition + 15000)
                //musicService!!.setSeekToPosition(musicService!!.getCurrentPosition() + 15000)
            }

            R.id.tv_timer_close -> {
                val bottomTimerDialog = BottomTimerDialog(this, object : BottomTimerDialog.OnClickListListener {
                    override fun onListClickListener(dialog: BottomTimerDialog, timeName: String, time: Long) {
                        dialog.dismiss()
                        flag = 0
                        if (time.toInt() == 0) {
                            ToastUtils.showShort("定时关闭已取消！")
                            tv_timer_close.text = "定时关闭"
                        }
                        if (time.toInt() == 1) {
                            tv_timer_close.text = "播放完本条关闭"
                        } else {
                            val timerIntent = Intent()
                            timerIntent.setClass(this@AudioActivity, TimerService::class.java)
                            timerIntent.putExtra("TIMER_CLOSE", time)
                            startService(timerIntent)
                            ToastUtils.showShort(timeName)
                        }

                    }
                })
                bottomTimerDialog.show()
            }

            R.id.rl_like -> {
                val map = HashMap<String, Int>()
                map["knowledgeId"] = musicId
                map["userId"] = MyApp.instance().userAccount!!.id
                val jsonObj = JSONObject(map)
                OkGo.post<String>(NetConstant.REQUEST_HEADER + NetApi.API_KNOWLEDGE_ADD_PRAISE)
                        .tag(this)
                        .upJson(jsonObj)
                        .execute(object : StringCallback() {
                            override fun onSuccess(response: Response<String>?) {
                                val josnObj = JSONObject(response!!.body())
                                val code = josnObj.getString("code")
                                if (code == "200") {
                                    tpv.setBackgroundResource(R.mipmap.ic_love_sel)
                                    tv_like.text = (tv_like.text.toString().toInt() + 1).toString()
                                    rl_like.isClickable = false
                                    //requestAudioInfo(musicId)
                                } else if (code == "503") {
                                    ToastUtils.showShort("您已经点赞啦~")
                                }
                            }
                        })
            }

            R.id.rl_download -> {

                if (ServiceUtils.isServiceRunning(FileDownloadService::class.java)) {
                    ToastUtils.showShort("有文件正在下载，请等待！")
                    return
                }

                val downloadIntent = Intent(this, FileDownloadService::class.java)
                downloadIntent.putExtra("FILE_URL", musicUrl)
                downloadIntent.putExtra("FILE_NAME", "${tv_audio_title.text}.mp3")
                downloadIntent.putExtra("FILE_ID", musicId)

                startService(downloadIntent)
            }

            R.id.rl_document -> {
                val intent = Intent()
                intent.setClass(this, WebActivity::class.java)
                intent.putExtra("document_url", "")
                intent.putExtra("document_title", tv_audio_title.text)
                intent.putExtra("document_id", musicId)
                startActivity(intent)
            }

            R.id.fl_next -> {
                ToastUtils.showShort("没有下一条")
            }
            R.id.fl_previous -> {
                ToastUtils.showShort("没有上一条")
            }
            R.id.rl_share -> {
                val intent = Intent(this, ContactActivity::class.java)
                intent.putExtra("KNOWLEDGE_ID", musicId)
                startActivity(intent)
            }
            else -> {
            }
        }
    }

    override fun bindService() {
        val intent = Intent(this, MusicService::class.java)
        bindService(intent, conn, AppCompatActivity.BIND_AUTO_CREATE)
    }


    private var conn = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val myBinder = service as (MusicService.MyBinder)
            musicService = myBinder.getService()
            mPlayerManager = musicService!!.getPlayerManager()
            mPlayerManager!!.addListenerCallback(this@AudioActivity)
            val audioInfo = mPlayerManager!!.getAudioInfo()
            musicId = audioInfo!!.id
            musicUrl = audioInfo.path
            tv_audio_title.text = audioInfo.name
            GlideUtils.showRoundImageFade(this@AudioActivity, audioInfo.img, iv_audio_avatar, 20, 20, RoundedCornersTransformation.CornerType.ALL)
            GlideUtils.showBlurImage(this@AudioActivity, audioInfo.img, iv_audio_bg, 25)
            if (mPlayerManager!!.getCurrentMediaPlayerState()) {
                playPauseDrawable.setPause(true)
            } else {
                playPauseDrawable.setPlay(true)
            }
            tv_end.text = currentDuration.format(mPlayerManager!!.getMusicDuration())
            sb_progress.max = mPlayerManager!!.getMusicDuration()

            val commentPresenter = CommentPresenter()
            val isDownload = commentPresenter.isDownloading("${mPlayerManager!!.getAudioInfo()!!.name}.mp3")
            if (isDownload) {
                tv_download.text = "已下载"
                rl_download.isClickable = false
            }


            commentPresenter.requestKnowledgeDetail(musicId, object : CommentPresenter.RequestKnowledgeDetailCallback {
                override fun requestKnowledgeDetailsSucceed(knowledgeTitle: String, knowledgeContent: String, createDate: Long, browseNum: Int, isCollect: Int, isPraise: Int, praiseNum: Int, coverImg: String, author: String, knowledgeDescribe: String, fileAddress: String) {
                    if (isPraise == 1) {
                        tpv.setBackgroundResource(R.mipmap.ic_love_sel)
                        rl_like.isClickable = false
                    }
                    tv_like.text = praiseNum.toString()
                }
            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(conn)
    }

    override fun onPlayerMediaPrepared() {

    }

    override fun onPlayerCurrentPosition(currentPosition: Int) {
        this.currentPosition = currentPosition
        tv_start.text = currentDuration.format(currentPosition)
        sb_progress.max = mPlayerManager!!.getMusicDuration()
        sb_progress.progress = currentPosition
        tv_end.text = currentDuration.format(mPlayerManager!!.getMusicDuration())
        if (mPlayerManager!!.getCurrentMediaPlayerState()) {
            playPauseDrawable.setPause(true)
        } else {
            playPauseDrawable.setPlay(true)
        }
    }

    override fun onPlayerBarVisibleState(isVisible: Boolean) {

    }

    override fun onPlayerStart(isFirstLoading: Boolean) {
        playPauseDrawable.setPause(true)
    }

    override fun onPlayerPause() {
        playPauseDrawable.setPlay(true)
    }

    override fun onPlayerStop() {

    }

    override fun onPlayMusicComplete() {
        playPauseDrawable.setPlay(true)
    }
}
